<template>
	<uni-popup ref="checkProvinceBox" :is-mask-click="!!provinceInfo.province_name" @maskClick="_close()" safeArea
		backgroundColor="transparent">
		<view class="provinceList">
			<view class="province_title">选择升本省份</view>
			<view class="province_desc">请选择升本省份，以便推荐{{ isLiscation ? '相关报考数据' : '课程' }}</view>
			<view class="now_location">
				<view class="location_left">
					<image src="https://bicpic.baikewang.com/images/1689752575484.png" mode="widthFix"></image>
					<view class="location_title1">当前省份</view>
				</view>
				<!-- <view class="location_right" @click="fnGetlocation()">
					<text class="iconfont icon-a-Frame1094-copy"></text>
					<view class="location_title2">重新定位</view>
				</view> -->
			</view>

			<view class="now_province">
				<text class="province_lis" @click.stop="checkProvince(provinceInfo)">
					{{ provinceInfo.province_name || '选择省份' }}
				</text>
			</view>
			<!-- 热门省份 -->
			<view class="hot_title" v-if="hotProvince.length">热门省份</view>
			<!-- 省份列表 -->
			<view class="uls">
				<text class="province_lis" @click.stop="checkProvince(item)"
					:class="{ active: item.province_id === provinceInfo.province_id }"
					v-for="(item, index) in hotProvince" :key="index">
					{{ item.province_name }}
					<text class="check iconfont icon-a-Frame1078"
						v-if="item.province_id === provinceInfo.province_id"></text>
				</text>
			</view>
			<view class="provinceUls" v-for="(item, index) in newProvinceList" :key="index">
				<!-- 省份分区 -->
				<view class="hot_title">{{ item.pinyin }}</view>
				<!-- 省份列表 -->
				<view class="uls">
					<text class="province_lis" :class="{ active: lis.province_id === provinceInfo.province_id }"
						@click.stop="checkProvince(lis)" v-for="(lis, lis_index) in item.list" :key="lis_index">
						{{ lis.province_name }}
						<!-- √icon   active才显示 -->
						<text class="check iconfont icon-a-Frame1078"
							v-if="lis.province_id === provinceInfo.province_id"></text>
						<!-- <view class="dui"></view> -->
					</text>
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
import PinyinUtils from '@/static/js/pinyinUtils.js';
export default {
	name: 'checkProvince',
	props: {
		isShow: {
			default: false
		},
		isLiscation: {
			default: false
		}
	},
	watch: {
		isShow(curr) {
			if (curr) {
				this.openPopup();
			}
		}
	},
	data() {
		return {
			newProvinceList: [],
			provinceInfo: {},
			location: {},
			hotProvince: [],
			isClick: true
		};
	},
	methods: {
		async checkProvince(obj) {
			let that = this;
			if (that.isLiscation) {
				that.provinceInfo = Object.assign({}, obj);
				uni.setStorageSync('provinceLiscationInfo', that.provinceInfo);
				getApp().globalData.provinceLiscationInfo = that.provinceInfo;
				that.$refs.checkProvinceBox.close();
				that.$store.commit('changeIsShow', false);
				that._close();
				return;
			}
			if (!obj.province_id) return;
			if (!that.isClick) return;
			that.isClick = false;
			uni.showLoading({
				title: '获取省份信息...',
				mask: true
			});
			getApp().getStaticInfo(obj.province_id);
			let provinceInfo = await that.getProvinceDetail(obj.province_id);
			that.provinceInfo = Object.assign({}, obj, provinceInfo);
			if (!getApp().globalData.token) {
				that.$refs.checkProvinceBox.close();
				that.$store.commit('changeIsShow', false);
				that._close();
				that.isClick = true;
				uni.hideLoading();
				return;
			}
			let { code, data } = await that.$application_api.setProvince({}, false);
			if (code != 0) {
				that.isClick = true;
				uni.hideLoading();
				return;
			}
			await that.getSelfInfo();
			that.$refs.checkProvinceBox.close();
			that.$store.commit('changeIsShow', false);
			that._close();
			uni.hideLoading();
			that.isClick = true;
		},
		_close() {
			let that = this;
			if (!that.provinceInfo.province_name) {
				uni.showToast({
					icon: 'none',
					title: '请选择所属省份'
				});
				return;
			}
			uni.setStorageSync('location', that.location);
			getApp().globalData.locatinProvince = that.location;
			that.$emit('_close');
		},
		openPopup() {
			let that = this;
			if (that.isLiscation) {
				that.provinceInfo = getApp().globalData.provinceLiscationInfo;
			}else{
				that.provinceInfo = getApp().globalData.provinceInfo;
			}
			that.$refs.checkProvinceBox.open('bottom');
			that.formatterProvince();
			let location = uni.getStorageSync('location');
			that.location = location;
			// if (!location.province_id) {
			// that.fnGetlocation();
			// }
		},
		// 定位获取
		fnGetlocation() {
			let that = this;
			uni.showLoading({
				title: '正在获取定位...',
				mask: true
			});
			uni.getLocation({
				type: 'wgs84',
				geocode: true,
				success: function (res) { },
				complete: async (info) => {
					let location = `${info.latitude},${info.longitude}`;
					let { code, data } = await that.$application_api.getLocationInfo({ location: location });
					uni.hideLoading();
					if (code != 0) {
						uni.showToast({
							icon: 'none',
							title: '定位失败，请手动选择省份'
						});
						return;
					}
					that.location = data;
				}
			});
		},
		formatterProvince() {
			let that = this;
			//调用
			that.sortName(that.provinceList, 'province_name');
		},
		//排序函数
		sortName(arr, eachName) {
			let that = this;
			arr.forEach(function (item) {
				let temp = item[eachName];
				item.sortName = temp;
				item.firstPinyin = PinyinUtils.chineseToPinYinFirst(item.sortName).substring(0, 1); // 第一个字首字母
				item.seconedPinyin = PinyinUtils.chineseToPinYinFirst(item.sortName).substring(1, 2); // 第二个字的首字母
			});
			let resultArray = arr.sort(function compareFunction(param1, param2) {
				//先按拼音首字母排序
				if (param1.firstPinyin > param2.firstPinyin) {
					return 1;
				} else if (param1.firstPinyin == param2.firstPinyin) {
					if (param1.seconedPinyin > param2.seconedPinyin) {
						//根据第二个汉字首字母排序
						return 1;
					} else if (param1.time < param2.time) {
						//按时间降序
						return 1;
					} else {
						return -1;
					}
				} else {
					return -1;
				}
			});
			that.splitProvince(resultArray);
		},
		// 切割省份分组
		// arr 要切割的数组  num 几位切割在一起
		splitProvince(arr, num = 5) {
			let that = this;
			let splitPinyin = {}; // 记录拼音所在的数组下表
			let splitArr = [];
			let finishedArr = [];
			arr.forEach((item) => {
				let all = Object.keys(splitPinyin);
				if (!all.includes(item.firstPinyin)) {
					// // console.log(item.firstPinyin);
					splitPinyin[item.firstPinyin] = splitArr.length;
					splitArr[splitPinyin[item.firstPinyin]] = [];
				}
				splitArr[splitPinyin[item.firstPinyin]].push(item);
			});
			splitArr.forEach((item, index) => {
				let _index = Math.floor(index / num); // 应该在第几组
				if (!finishedArr[_index]) {
					finishedArr[_index] = { pinyin: item[0].firstPinyin, list: [] };
				} else {
					finishedArr[_index].pinyin += `-${item[0].firstPinyin}`;
				}
				finishedArr[_index].list = finishedArr[_index].list.concat(item);
			});
			that.newProvinceList = finishedArr;
		},
		async getHotProvinceList() {
			let that = this;
			let { code, data } = await that.$application_api.getHotProvinceList({}, false);
			if (code != 0) return;
			that.hotProvince = data;
		},
		async getProvinceList() {
			let that = this;
			that.provinceList = getApp().globalData.provinceList;
			if (!that.provinceList || !that.provinceList.length) {
				await getApp().appGetProvinceList();
				that.provinceList = getApp().globalData.provinceList;
			}
			// 格式化省份列表
			that.formatterProvince();
		}
	},
	mounted() {
		if (!this.provinceList.length) {
			this.getProvinceList();
		}
		if (!this.hotProvince.length) {
			this.getHotProvinceList();
		}
	}
};
</script>

<style lang="scss" scoped>
.provinceList {
	width: 100vw;
	min-height: 20vh;
	max-height: 86vh;
	border-radius: 40rpx 40rpx 0 0;
	background-color: #ffffff;
	padding: 40rpx 40rpx calc(40rpx + env(safe-area-inset-bottom));
	box-sizing: border-box;
	overflow-y: auto;

	.province_title {
		font-size: 53rpx;
		color: #121317;
		font-weight: bold;
		line-height: 85rpx;
	}

	.province_desc {
		font-size: 27rpx;
		color: #858688;
		line-height: 42rpx;
	}

	.now_location {
		width: 100%;
		margin-top: 68rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.location_left {
			flex-shrink: 0;
			display: flex;
			align-items: center;
			justify-content: flex-start;

			image {
				margin-top: 14rpx;
				width: 46rpx;
				height: 46rpx;
			}
		}

		.location_right {
			flex-shrink: 0;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.location_title1 {
			font-size: 38rpx;
			color: #232a35;
			font-weight: bold;
			margin-left: 4rpx;
		}

		.location_title2 {
			font-size: 27rpx;
			color: #121317;
			font-weight: 400;
			margin-left: 10rpx;
		}
	}

	.now_province {
		margin-top: 24rpx;

		.province_lis {
			font-weight: bold;
		}
	}
}

.province_lis {
	width: calc((100% - 29rpx * 3) / 4);
	display: inline-flex;
	align-content: center;
	justify-content: center;
	height: max-content;
	font-size: 31rpx;
	color: #121317;
	background-color: #f8f8f8;
	border: 4rpx solid #f8f8f8;
	border-radius: 20rpx;
	padding: 23rpx 0;
	box-sizing: border-box;
	overflow: hidden;
}

.province_lis.active {
	border-color: #007aff;
	position: relative;
	font-weight: bold;
	color: #007aff;
}

.check {
	color: #ffffff;
	position: absolute;
	right: 0;
	bottom: 0;
	z-index: 1;
	border-radius: 26rpx 0rpx 19rpx 0rpx;
	padding: 9rpx 10rpx;
	box-sizing: border-box;
	background-color: #007aff;
	transform: translate(20%, 20%) scale(0.8);
	font-size: 22rpx;
	color: #ffffff;
	font-weight: normal;
}

.hot_title {
	margin-top: 64rpx;
	font-size: 39rpx;
	color: #121317;
	font-weight: bold;
}

.uls {
	width: 100%;
	display: grid;
	grid-gap: 29rpx 30rpx;
	grid-template-areas: '. . . .';
	margin-top: 24rpx;

	>.province_lis {
		width: 100%;
	}
}
</style>
